package com.cade.agriculturemall.view.personalCenter.discount.myDiscountFragment;

import android.text.TextUtils;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.cade.agriculturemall.base.BasePresenter;
import com.cade.agriculturemall.model.Ticket;
import com.cade.agriculturemall.model.UserInfoEntity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by hshunxin on 2018/2/27.
 */

public class MyDiscountPresenter extends BasePresenter<MyDiscountContract.IView> implements MyDiscountContract.IPresenter {
    public MyDiscountPresenter(MyDiscountContract.IView view) {
        super(view);
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {

    }

    AVQuery<Ticket> entityAVQuery = new AVQuery<>("ticket_discount");
    UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
    String currentUserId = user.getObjectId();

    @Override
    public void downTicket() {
        final Date date = new Date();
        final List<Ticket> activeList = new ArrayList<>();
        final List<Ticket> noActiveList = new ArrayList<>();
        entityAVQuery.whereEqualTo("user_id", currentUserId);
        entityAVQuery.findInBackground(new FindCallback<Ticket>() {
            @Override
            public void done(List<Ticket> list, AVException e) {
                if (e == null) {
                    for (Ticket entity : list) {
                        int i = date.compareTo(entity.getEndTime());
//                                entity.getHadUse()： 0——待使用   1——已使用
                        if (entity.getHadUse().equals("0")) {
                            if (i >= 0) {
                                noActiveList.add(entity);
                            } else {
                                activeList.add(entity);
                            }
                        } else {
                            noActiveList.add(entity);
                        }
                    }
                    mView.getMyDiscount(activeList, noActiveList);
                } else {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void deleteMyTicket(String ticketId) {
        AVObject avObject = AVObject.createWithoutData("ticket_discount", ticketId);
        avObject.put("user_id", "");
        avObject.saveInBackground(new SaveCallback() {
            public void done(AVException e) {
                if (e == null) {
                    mView.showMessage("成功！");
                }
            }
        });
    }
}
